package com.toonyoo.eurekaproducer.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@MapperScan(basePackages = "com.toonyoo.eurekaproducer.dao.test1", sqlSessionFactoryRef = "testSqlSessionFactoryBean")
public class TestDataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.test1")
    public DataSourceProperties testDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "testDataSource")
    public DataSource testDataSource() {
        return testDataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean(name = "testSqlSessionFactoryBean")
    public SqlSessionFactoryBean testSqlSessionFactoryBean(@Qualifier("testDataSource") DataSource testDataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(testDataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/test1/*.xml"));
        return sqlSessionFactoryBean;
    }

    @Bean(name = "testSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("testSqlSessionFactoryBean") SqlSessionFactoryBean testSqlSessionFactoryBean) throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(testSqlSessionFactoryBean.getObject());
        return template;
    }
}
